package com.example.springboot.controller;

import cn.hutool.core.util.StrUtil;
import com.alipay.api.domain.Account;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.example.springboot.Exception.ServiceException;
import com.example.springboot.common.Result;
import com.example.springboot.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 管理员表(Admin)表控制层
 *
 * @author makejava
 * @since 2024-01-13 17:16:25
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    /**
     * 服务对象
     */
    @Autowired
    private AdminService adminService;


    /**
     * 添加管理员
     *
     * @param admin
     * @return
     */
    @PostMapping("/addAdmin")
    public Result addAdmin(@RequestBody Admin admin) {
        System.out.println(admin.toString());
        return Result.success();
    }


    /**
     * 获取所有管理员信息
     */
    @GetMapping("/selectAll")
    public Result selectAll() {
        return Result.success(adminService.selectAll());
    }


    /**
     * 通过主键查询单条数据
     *
     * @param account
     * @param request
     * @return
     */
    @PutMapping("/changePassword")
    public Result changePassword(@RequestBody Account account, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("token");
        }
        String id;
        try {
            id = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new ServiceException("401", "请登录");
        }
        account.setId(Integer.valueOf(id));
        account.setToken(token);
        adminService.changePassword(account);
        return Result.success();
    }

    /**
     * 通过主键删除数据
     *
     * @param admin
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody Account admin) {

        adminService.update(admin);
        return Result.success("更新成功");
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id
     * @return
     */
    @GetMapping("/getUserInfo/{id}")
    public Result getUserInfo(@PathVariable("id") Integer id) {
        Account userInfo = adminService.getUserInfo(id);
        userInfo.setRole("管理员");
        return Result.success(userInfo);
    }


}

